package com.luo.jiuyuetest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luo.jiuyuetest.dto.ProductDTO;
import com.luo.jiuyuetest.dto.ProductPartDTO;
import com.luo.jiuyuetest.dto.SupplierAddRequest;
import com.luo.jiuyuetest.dto.SupplierInfoDTO;
import com.luo.jiuyuetest.entity.Product;
import com.luo.jiuyuetest.entity.Productpart;
import com.luo.jiuyuetest.entity.Supplier;
import com.luo.jiuyuetest.mapper.ProductMapper;
import com.luo.jiuyuetest.mapper.ProductpartMapper;
import com.luo.jiuyuetest.mapper.SupplierMapper;
import com.luo.jiuyuetest.service.SupplierService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.luo.jiuyuetest.dto.SupplierTreeDTO;
import com.luo.jiuyuetest.dto.ProductTreeDTO;
import com.luo.jiuyuetest.dto.PartTreeDTO;


import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 供应商服务实现类
 */
@Service
public class SupplierServiceImpl extends ServiceImpl<SupplierMapper, Supplier> implements SupplierService {

    @Autowired
    private SupplierMapper supplierMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductpartMapper productpartMapper;

    /**
     * 添加供应商及其产品和零件（带事务）
     * @param request 请求参数
     * @return 成功消息
     */
    @Transactional(rollbackFor = Exception.class)
    public String addSupplierWithProducts(SupplierAddRequest request) {
        // 1. 创建供应商
        Supplier supplier = new Supplier();
        supplier.setCode(UUID.randomUUID().toString());  // 生成 UUID
        supplier.setName(request.getName());
        supplier.setContactperson(request.getContactperson());
        supplier.setContactphone(request.getContactphone());
        supplier.setAddress(request.getAddress());
        supplier.setCreatetime(LocalDateTime.now());
        supplier.setStatus("正常");  // 设置默认状态

        // 保存供应商到数据库
        supplierMapper.insert(supplier);
        System.out.println("供应商插入成功，ID: " + supplier.getId() + ", Code: " + supplier.getCode());

        // 2. 遍历产品列表
        if (request.getProducts() != null && !request.getProducts().isEmpty()) {
            for (ProductDTO productDTO : request.getProducts()) {
                // 创建产品
                Product product = new Product();
                product.setCode(UUID.randomUUID().toString());  // 生成 UUID
                product.setName(productDTO.getName());
                product.setSuppliercode(supplier.getCode());  // 关联供应商 code
                product.setCategory(productDTO.getCategory());
                product.setPrice(productDTO.getPrice());
                product.setCreatetime(LocalDateTime.now());

                // 保存产品到数据库
                productMapper.insert(product);
                System.out.println("产品插入成功，ID: " + product.getId() + ", Name: " + product.getName());

                // 3. 遍历该产品下的零件列表
                if (productDTO.getParts() != null && !productDTO.getParts().isEmpty()) {
                    for (ProductPartDTO partDTO : productDTO.getParts()) {
                        // 创建零件
                        Productpart part = new Productpart();
                        part.setCode(UUID.randomUUID().toString());  // 生成 UUID
                        part.setName(partDTO.getName());
                        part.setPid(product.getId());  // 关联产品 ID
                        part.setCategory(partDTO.getCategory());
                        part.setCost(partDTO.getCost());
                        part.setCreatetime(LocalDateTime.now());

                        // 保存零件到数据库
                        productpartMapper.insert(part);
                        System.out.println("零件插入成功，ID: " + part.getId() + ", Name: " + part.getName());
                    }
                }
            }
        }

        return "供应商及其产品、零件添加成功！供应商: " + supplier.getName() + ", 产品数: " + request.getProducts().size();
    }

    /**
     * 查询供应商列表（支持模糊查询）
     * @param name 供应商名称（可选，用于模糊查询）
     * @return 供应商基本信息列表
     */
    @Override
    public List<SupplierInfoDTO> getSupplierList(String name) {
        // 1. 构建查询条件
        QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();

        // 如果传入了名称，进行模糊查询
        if (name != null && !name.trim().isEmpty()) {
            queryWrapper.like("name", name);
            System.out.println("模糊查询供应商，关键词: " + name);
        } else {
            System.out.println("查询所有供应商");
        }

        // 2. 查询供应商列表
        List<Supplier> suppliers = supplierMapper.selectList(queryWrapper);

        // 3. 转换为 DTO 列表
        List<SupplierInfoDTO> result = new ArrayList<>();
        for (Supplier supplier : suppliers) {
            SupplierInfoDTO dto = new SupplierInfoDTO();
            // 使用 BeanUtils 复制属性（字段名相同的会自动复制）
            BeanUtils.copyProperties(supplier, dto);
            result.add(dto);
        }

        System.out.println("查询到 " + result.size() + " 个供应商");
        return result;
    }

    /**
     * 删除指定供应商及其所有产品和零件（级联删除）
     * @param supplierName 供应商名称
     * @return 删除结果消息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String deleteSupplierWithRelated(String supplierName) {
        System.out.println("=== 开始删除供应商及其关联数据 ===");
        System.out.println("供应商名称: " + supplierName);

        // 1. 查询供应商
        QueryWrapper<Supplier> supplierWrapper = new QueryWrapper<>();
        supplierWrapper.eq("name", supplierName);
        Supplier supplier = supplierMapper.selectOne(supplierWrapper);

        if (supplier == null) {
            return "未找到供应商: " + supplierName;
        }

        System.out.println("找到供应商，ID: " + supplier.getId() + ", Code: " + supplier.getCode());

        // 2. 查询该供应商的所有产品
        QueryWrapper<Product> productWrapper = new QueryWrapper<>();
        productWrapper.eq("suppliercode", supplier.getCode());
        List<Product> products = productMapper.selectList(productWrapper);

        if (products != null && !products.isEmpty()) {
            // 3. 获取产品ID列表
            List<Integer> productIds = products.stream()
                    .map(Product::getId)
                    .collect(Collectors.toList());

            System.out.println("找到产品数量: " + products.size() + ", ID列表: " + productIds);

            // 4. 删除所有零件（先删除子数据）
            QueryWrapper<Productpart> partWrapper = new QueryWrapper<>();
            partWrapper.in("pid", productIds);
            int partCount = productpartMapper.delete(partWrapper);
            System.out.println("删除零件数量: " + partCount);

            // 5. 删除所有产品
            int productCount = productMapper.delete(productWrapper);
            System.out.println("删除产品数量: " + productCount);
        } else {
            System.out.println("该供应商下没有产品");
        }

        // 6. 删除供应商
        int supplierCount = supplierMapper.deleteById(supplier.getId());
        System.out.println("删除供应商数量: " + supplierCount);

        System.out.println("=== 删除完成 ===");

        return "成功删除供应商【" + supplierName + "】及其关联的所有产品和零件";
    }

    /**
     * 生成供应商-产品-零件的树形结构
     * @return 树形结构数据
     */
    @Override
    public List<SupplierTreeDTO> getTreeStructure() {
        System.out.println("=== 开始生成树形结构 ===");

        // 1. 查询所有供应商
        List<Supplier> suppliers = supplierMapper.selectList(null);
        System.out.println("查询到供应商数量: " + suppliers.size());

        // 2. 查询所有产品
        List<Product> products = productMapper.selectList(null);
        System.out.println("查询到产品数量: " + products.size());

        // 3. 查询所有零件
        List<Productpart> parts = productpartMapper.selectList(null);
        System.out.println("查询到零件数量: " + parts.size());

        // 4. 构建树形结构
        List<SupplierTreeDTO> tree = new ArrayList<>();

        for (Supplier supplier : suppliers) {
            // 创建供应商节点
            SupplierTreeDTO supplierNode = new SupplierTreeDTO();
            supplierNode.setId(supplier.getId().toString());
            supplierNode.setCode(supplier.getCode());
            supplierNode.setName(supplier.getName());

            // 查找该供应商的所有产品
            List<ProductTreeDTO> productNodes = new ArrayList<>();
            for (Product product : products) {
                if (supplier.getCode().equals(product.getSuppliercode())) {
                    // 创建产品节点
                    ProductTreeDTO productNode = new ProductTreeDTO();
                    productNode.setId(product.getId().toString());
                    productNode.setCode(product.getCode());
                    productNode.setName(product.getName());

                    // 查找该产品的所有零件
                    List<PartTreeDTO> partNodes = new ArrayList<>();
                    for (Productpart part : parts) {
                        if (product.getId().equals(part.getPid())) {
                            // 创建零件节点
                            PartTreeDTO partNode = new PartTreeDTO();
                            partNode.setId(part.getId().toString());
                            partNode.setCode(part.getCode());
                            partNode.setName(part.getName());
                            partNodes.add(partNode);
                        }
                    }

                    productNode.setChildren(partNodes);
                    productNodes.add(productNode);
                }
            }

            supplierNode.setChildren(productNodes);
            tree.add(supplierNode);
        }

        System.out.println("生成树形结构节点数: " + tree.size());
        System.out.println("=== 树形结构生成完成 ===");

        return tree;
    }
}